<?php

// +----------------------------------------------------------------------
// | Easyadmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\statistics;


//公共

use app\admin\model\website\Rooms;
use app\admin\model\website\Users as UsersModel;
use app\common\controller\AdminController;
use broadcast\redis\setRedis;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="站点管理")
 */
class LineUsers extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post();
            if (!isset($params['type']) or empty($params['type'])) {
                $params['type'] = 0;
            }
            if (!isset($params['date']) or empty($params['date'])) {
                $params['date'] = date('Y-m-d');
            }

            if (!isset($params['start_time']) or empty($params['start_time'])) {
                $params['start_time'] = date('H:i:s', strtotime("- 1hour"));
            }

            if (!isset($params['end_time']) or empty($params['end_time'])) {
                $params['end_time'] = date('H:i:s');
            }

            // 获取查看时间范围
            $lables = $this->getTimeList(strtotime($params['date'] . ' ' . $params['start_time']), strtotime($params['date'] . ' ' . $params['end_time']));

            // 获取查看房间范围
            $roomsData = $this->getAdminRooms(session('admin'), $lables, $params);
            $data = compact('lables', 'roomsData', 'params');
            return json($data);
        }

        // 在线统计表格数据
        $now_date = date('Y-m-d');
        $now_minute = date('H:i');
        $rooms = $this->getDataStatistics(session('admin'));
        $roomsData = [];

        $total_users_nums = 0;
        $total_tourist_nums = 0;
        $total_nums = 0;
        $total_register_nums = 0;

        if (!$rooms) {
            if (session('admin.group') == 6) {
                // 房间管理员看该房间所有房间管理员、所有业务员、总的在线用户
                // 查询房间管理员
                $roomKeeper = UsersModel::where(['rooms' => session('admin.rooms'), 'group' => session('admin.group')])->column('username');
                // 查询此房间管理员下的业务员
                $salesman = UsersModel::where(['rooms' => session('admin.rooms'), 'group' => 7, 'extension' => session('admin.username')])->column('username');
                $users = array_merge($roomKeeper, $salesman);
            } elseif (session('admin.group') == 7) {
                // 业务员看自己的、总的在线用户
                $users = [session('admin.username')];
            }
            $roomId = session('admin.rooms');
            foreach ($users as $item) {
                $res = setRedis::getRoomsData(session("website"), "onlineData:{$now_date}:rid:{$roomId}", $now_minute);
                if ($res) {
                    $res = json_decode($res[$now_minute], true);
                    $nums = 0;
                    if (isset($res[$item])) {
                        $nums = $res[$item];
                    }
                    $total_users_nums += $nums;
                    $roomsData[] = ['rid' => $item, 'users_nums' => $nums];
                } else {
                    $roomsData[] = ['rid' => $item, 'users_nums' => 0];
                }
            }

        } else {
            foreach ($rooms as $item) {
                $res = setRedis::getRoomsData(session("website"), "onlineData:{$now_date}:rid:{$item}", $now_minute);
                $register_nums = setRedis::getRegisterCount(session("website"), date('Y-m-d'), $item);
                $total_register_nums += $register_nums;
                if ($res) {
                    $res = json_decode($res[$now_minute], true);
                    if (!isset($res['tourist_nums'])) {
                        $res['tourist_nums'] = 0;
                    }
                    if (!isset($res['users_nums'])) {
                        $res['users_nums'] = 0;
                    }

                    $total_users_nums += $res['users_nums'];
                    $total_tourist_nums += $res['tourist_nums'];
                    $total_nums += $res['users_nums'] + $res['tourist_nums'];

                    $roomsData[] = ['rid' => $item, 'users_nums' => $res['users_nums'], 'tourist_nums' => $res['tourist_nums'], 'total_nums' => $res['users_nums'] + $res['tourist_nums'], 'register_nums' => $register_nums];
                } else {
                    $roomsData[] = ['rid' => $item, 'users_nums' => 0, 'tourist_nums' => 0, 'total_nums' => 0, 'register_nums' => $register_nums];
                }
            }
        }
        array_unshift($roomsData, ['rid' => '全部', 'users_nums' => $total_users_nums, 'tourist_nums' => $total_tourist_nums, 'total_nums' => $total_nums, 'register_nums' => $total_register_nums]);
        $this->assign('adminGroup', session('admin.group'));
        $this->assign('roomsData', $roomsData);
        return $this->fetch();
    }

    public function getNowData()
    {
        $now_date = date('Y-m-d');
        $show_time = date('H:i');
        halt($this->getAdminRooms(session('admin'), [$show_time], ['type' => 0, 'date' => $now_date]));
    }

    public function getDataStatistics($admin)
    {

        if ($admin['group'] == 1) {
            $rooms = Rooms::where(['status' => 1])->column('roomid');
        } elseif ($admin['group'] == 5) {
            $rooms = explode(',', $admin['rooms']);
        } else {
//            $rooms = [$admin['rooms']];
            $rooms = false;
        }
        return $rooms;

    }


    private function getAdminRooms($admin, $lables, $params)
    {

        $now_date = date('Y-m-d', strtotime($params['date']));

        // 查询房间数据
        $temp_1 = [];
        foreach ($lables as $value) {
            $now_minute = date('H:i', strtotime($value));
            $temp_1[] = $now_minute;
        }

        switch ($admin['group']) {
            case 1:
            case 5:
                if ($admin['group'] == 1) {
                    // 超级管理员 查看所有
                    $legend = Rooms::where(['status' => 1])->column('roomid');
                } else {
                    $legend = explode(',', $admin['rooms']);
                }
                $series = [];
                foreach ($legend as &$item) {
                    $data = ['name' => '房间' . $item, 'type' => 'line', 'data' => []];
                    $RoomsData = setRedis::getRoomsData(session("website"), "onlineData:{$now_date}:rid:{$item}", $temp_1);
                    $data['data'] = $this->getRoomsData($RoomsData, $params);
                    $series[] = $data;
                    $item = "房间" . $item;
                }

                // 获取房间总人数
                $totalNumber = [];
                $tempArr = [];
                foreach ($series as $value) {
                    foreach ($value['data'] as $index => $item) {
                        $tempArr[$index][] = $item;
                    }
                }
                foreach ($tempArr as $item) {
                    $totalNumber[] = array_sum($item);
                }

                array_unshift($series, ['name' => '所有房间', 'data' => $totalNumber, 'type' => 'line']);
                array_unshift($legend, '所有房间');
                return ['legend' => $legend, 'series' => $series];
            case 6:
                // 查询房间管理员
                $roomAdminList = UsersModel::where(['rooms' => $admin['rooms'], 'group' => $admin['group']])->column('username');

                $RoomsData = setRedis::getRoomsData(session("website"), "onlineData:{$now_date}:rid:{$admin['rooms']}", $temp_1);

                $data = $this->getRoomsData($RoomsData, $params, $roomAdminList);
                $legend[] = '房间' . $admin['rooms'];
                foreach ($data as $k => $value) {
                    if ($k == 'room') {
                        $series[] = ['name' => '房间' . $admin['rooms'], 'type' => 'line', 'data' => $value];
                    } else {
                        $legend[] = '管理' . $k;
                        $series[] = ['name' => '管理' . $k, 'type' => 'line', 'data' => $value];
                    }
                }
                return ['legend' => $legend, 'series' => $series];
            case 7:
                // 房间业务员
                $roomAdminList = [$admin['username']];
                $RoomsData = setRedis::getRoomsData(session("website"), "onlineData:{$now_date}:rid:{$admin['rooms']}", $temp_1);
                $data = $this->getRoomsData($RoomsData, $params, $roomAdminList);
                $legend[] = '房间' . $admin['rooms'];
                foreach ($data as $k => $value) {
                    if ($k == 'room') {
                        $series[] = ['name' => '房间' . $admin['rooms'], 'type' => 'line', 'data' => $value];
                    } else {
                        $legend[] = $k;
                        $series[] = ['name' => $k, 'type' => 'line', 'data' => $value];
                    }
                }
                return ['legend' => $legend, 'series' => $series];
        }
    }

    private function getTimeList($stime, $etime)
    {
        while ($stime <= $etime) {
            $datearr[] = date('Y-m-d H:i', $etime); //得到dataarr的日期数组。
            $etime = $etime - 60 * 1;
        }
        return array_reverse($datearr);
    }

    /**
     * 获取房间数据
     */
    private function getRoomsData($RoomsData, $params, $roomAdminList = [])
    {
        foreach ($RoomsData as $val) {

            $val = json_decode($val, true);
            if (!is_array($val)) {
                $val = [];
            }
            if (!isset($val['users_nums'])) {
                $val['users_nums'] = 0;
            }
            if (!isset($val['tourist_nums'])) {
                $val['tourist_nums'] = 0;
            }

            if (!empty($roomAdminList)) {
                switch ($params['type']) {
                    case 0:
                        $data['room'][] = ($val['users_nums'] + $val['tourist_nums']);
                        break;
                    case 1:
                        $data['room'][] = $val['users_nums'];
                        break;
                    case 2:
                        $data['room'][] = $val['tourist_nums'];
                        break;
                }
            } else {
                switch ($params['type']) {
                    case 0:
                        $data[] = ($val['users_nums'] + $val['tourist_nums']);
                        break;
                    case 1:
                        $data[] = $val['users_nums'];
                        break;
                    case 2:
                        $data[] = $val['tourist_nums'];
                        break;
                }
            }

            // 房间管理员
            if ($roomAdminList) {
                foreach ($roomAdminList as $item) {
                    if (!isset($val[$item])) {
                        $data[$item][] = 0;
                    } else {
                        $data[$item][] = $val[$item];
                    }
                }
            }
        }
        return $data;
    }
}
